import React from "react";

// 导入顶部栏搜索
import SearchHeader from "../../components/SearchHeader";
import { Flex } from "antd-mobile-v2";
import { API } from "../../utils/api";
import { Toast } from 'antd-mobile'
import styles from './index.module.css'
import { withNavigation } from '../../utils/navigate'
import Filter from "./components/Filter";
import { List, AutoSizer, WindowScroller, InfiniteLoader } from 'react-virtualized'
import HouseItem from '../../components/HouseItem'
import { BASE_URL } from "../../utils/url";
import {getCurrentCity} from '../../utils'
// 导入吸顶组件
import Sticky from "../../components/Sticky";
// 当前页面无数据组件
import NoHouse from '../../components/NoHouse'
// 获取当前城市定位信息
// const { label,value } = JSON.parse(localStorage.getItem('hkzf_city'))
class HouseList extends React.Component {

    state = {
        // 数据列表
        list: [],
        // 总条数
        count: 0,
        // 是否在加载数据
        isLoading: false
    }
    label = ''
    value = ''

    // 状态初始化,避免为undefined
    filters = {}

    // 页面一进来需要获取数据
     async componentDidMount() {
        const {label,value} = await getCurrentCity()
        this.label = label
        this.value = value
        this.searchHouseList()
    }

    // 用来获取房屋列表数据
    async searchHouseList() {

        this.setState({
            isLoading: true
        })
        // 开启loading
        Toast.show({
            icon: 'loading',
            content: '加载中…',
        })
        const { data: res } = await API.get('/houses', {
            params: {
                cityId: this.value,
                ...this.filters,
                start: 1,
                end: 20
            }
        })
        const { list, count } = res.body
        // 关闭loading
        Toast.clear()
        // 提示房源数量
        Toast.show({
            content: `共找到${count}套房源`
        })
        this.setState({
            list,
            count,
            isLoading: false
        })
    }


    // 接收Filter组件中的筛选条件数据
    onFilter = (filters) => {
        window.scrollTo(0,0)
        this.filters = filters
        this.searchHouseList()
    }

    // 渲染每一行数据的渲染函数，通过他渲染内容
    renderHouseList = ({
        key, // Unique key within array of rows
        index, // 索引号
        style, // 注意：重点属性，一定要给每一行添加改样式，作用：指定每一行的位置
    }) => {
        // 根据我们的索引号来获取当前这一行的房屋数据
        const { list } = this.state
        const house = list[index]  //获取到每一项房屋的数据

        // 判断house是否存在
        // 如果不存在就渲染loading进行占位
        if (!house) {
            return <div key={key} style={style}>
                <p className={styles.loading}></p>
            </div>
        }
        const {navigate} = this.props

        return (
            <HouseItem key={key}
                style={style} 
                src={BASE_URL + house.houseImg}
                title={house.title}
                desc={house.desc}
                tags={house.tags}
                price={house.price}
                onClick={()=>navigate(`/detail/${house.houseCode}`)}
            />
        )
    }

    // 判断列表中的每一行是否加载完成
    isRowLoaded = ({ index }) => {
        return !!this.state.list[index];
    }
    // 用来获取更多的房屋列表数据
    // 注意：该方法的返回值是一个Promise对象，并且，这个对象应该在数据加载完成时，来调用resolve让Promise对象的状态变为完成
    loadMoreRows = ({ startIndex, stopIndex }) => {
        return new Promise(resolve => {
            API.get('/houses', {
                params: {
                    cityId: this.value,
                    ...this.filters,
                    start: startIndex,
                    end: stopIndex
                }
            }).then(res => {
                this.setState({
                    list: [...this.state.list, ...res.data.body.list]
                })
                // 数据加载完成时，调用resolve
                resolve()
            })
            // 数据加载完成时，调用resolve即可
        })
    }

    // 渲染列表数据
    renderList = () => {
        const { count, isLoading } = this.state
        // 关键点：在数据加载完成后，再进行count判断
        if (count === 0 && !isLoading) {
            return (
                <NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse>
            )
        }
        return (
            <InfiniteLoader
                isRowLoaded={this.isRowLoaded}
                loadMoreRows={this.loadMoreRows}
                rowCount={count}
            >
                {({ onRowsRendered, registerChild }) => (
                    <WindowScroller>
                        {({ height, isScrolling, scrollTop }) => (
                            <AutoSizer>
                                {({ width }) => (
                                    <List
                                        onRowsRendered={onRowsRendered}
                                        ref={registerChild}
                                        autoHeight //设置高度为WindowScroller最终渲染列表的列表高度
                                        width={width} //视口宽度
                                        height={height} //视口高度
                                        rowCount={count} //list 列表项的行数
                                        rowHeight={120} //每一行的高度
                                        rowRenderer={this.renderHouseList} //渲染列表中的每一行
                                        isScrolling={isScrolling}
                                        scrollTop={scrollTop}
                                    />
                                )}
                            </AutoSizer>
                        )}
                    </WindowScroller>
                )}
            </InfiniteLoader>
        )
    }


    render() {
        return (
            <div className={styles.root}>
                {/* 顶部导航栏 */}
                <Flex className={styles.header}>
                    <i className="icon-back iconfont" onClick={() => this.props.navigate(-1)}></i>
                    <SearchHeader cityName={this.label} className={styles.searchHeader} />
                </Flex>

                {/* 条件筛选栏 */}
                <Sticky height={40}>
                    <Filter onFilter={this.onFilter} />
                </Sticky>

                {/* 房屋列表 */}
                <div className={styles.houseItems}>
                    {this.renderList()}
                </div>
            </div>
        )
    }
}

export default withNavigation(HouseList)